/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.service.purchase;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.neusoft.lohas.common.persistence.Parameter;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.modules.ivm.dao.purchase.PurchaseDetailDao;
import com.neusoft.lohas.modules.ivm.entity.order.Order;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetail;
import com.neusoft.lohas.modules.ivm.entity.purchase.PurchaseDetail;
import com.neusoft.lohas.modules.ivm.entity.purchase.PurchaseDetailItem;

/**
 * 采购单详情Service
 * @author Jackie.Liu
 * @version 2014-12-29
 */
@Component
@Transactional(readOnly = true)
public class PurchaseDetailService extends BaseService {

	@Autowired
	private PurchaseDetailDao purchaseDetailDao;
	
	public PurchaseDetail get(String id) {
		return purchaseDetailDao.get(id);
	}
	
	public List<PurchaseDetail> getDetails(String purchaseInfoId, String supplierId){
		return purchaseDetailDao.getDetails(purchaseInfoId, supplierId);
	}
	
	@Transactional(readOnly = false)
	public void save(PurchaseDetail detail) {
		purchaseDetailDao.save(detail);
	}
	
	@Transactional(readOnly = false)
	public void save(List<PurchaseDetail> details) {
		purchaseDetailDao.save(details);
	}
	
	@Transactional(readOnly = false)
	public int delete(String id) {
		return purchaseDetailDao.deleteById(id);
	}
	
	/**
	 * 获取采购清单明细数据对应的订单详情
	 * @param id
	 * @param type
	 * @return
	 */
	public List<Order> getOrderDetails(String id){
		PurchaseDetail detail = purchaseDetailDao.get(id);
		String productId = detail.getProduct().getId();
		List<Order> orderList = detail.getOrderList();
		for (Order order : orderList) {
			List<OrderDetail> details = Lists.newArrayList();
			for (OrderDetail orderDetail : order.getDetailList()) {
				if (orderDetail.getProduct().getId().equals(productId)) {
					details.add(orderDetail);
				}
			}
			order.setDetailList(details);
		}
		return orderList;
	}
	
	@Transactional(readOnly = false)
	public int deletePurchaseDetailItem(String purchaseId, String productId){
		String ql = "update PurchaseDetailItem set delFlag=:p1 where purchase.id=:p2 and product.id=:p3";
		return purchaseDetailDao.update(ql, new Parameter(PurchaseDetailItem.DEL_FLAG_DELETE, purchaseId, productId));
	}

}
